#include "sprite.h"
#include "../../global/renderer.h"
#include "ui-renderer.h"
#include "../node.h"

enum SpriteFlag
{
    NONE = 0x00,
    VERTEX = 0x01,
    SHADER = 0x02,
    COLOR = 0x04,
    TEXTURE = 0x08,
    ALL = 0xFF,
};

Sprite::Sprite(Node *node) : _flag(SpriteFlag::ALL)
{
    this->_node = node;
    this->_rendererId = this->_getAddressString();
    this->_shaderPath = "resources/effects/default/default";
    this->_texturePath = "resources/ui/ic-default.png";

    this->_renderer = new UIRenderer(this->_rendererId);
}
std::string Sprite::_getAddressString()
{
    std::stringstream ss;
    ss << "CE_UISprite@0x"
       << std::hex << std::setw(sizeof(void *) * 2)
       << std::setfill('0')
       << reinterpret_cast<uintptr_t>(this);
    return ss.str();
}

Size &Sprite::size()
{
    return this->_size;
}
Vec2 &Sprite::anchor()
{
    return this->_anchor;
}
Color &Sprite::color()
{
    return this->_color;
}

void Sprite::setSize(float width, float height)
{
    this->_size.set(width, height);
    this->_flag |= SpriteFlag::VERTEX;
}

void Sprite::setAnchor(float x, float y)
{
    this->_anchor.set(x, y);
    this->_flag |= SpriteFlag::VERTEX;
}
void Sprite::setColor(float r, float g, float b, float a)
{
    this->_color.set(r, g, b, a);
    this->_flag |= SpriteFlag::COLOR;
}
void Sprite::setShader(std::string shaderPath)
{
    this->_shaderPath = shaderPath;
    this->_flag |= SpriteFlag::SHADER;
}
void Sprite::setTexture(std::string texturePath)
{
    this->_texturePath = texturePath;
    this->_flag |= SpriteFlag::TEXTURE;
}

void Sprite::update(float deltaTime)
{
    // 先更新渲染状态
    if (this->_flag & SpriteFlag::SHADER)
    {
        this->_renderer->updateShader(this->_shaderPath);
    }
    // 再更新顶点数据
    if (this->_flag & SpriteFlag::VERTEX)
    {
        this->_renderer->updateVertexs(this->_node->worldPosition().x(), this->_node->worldPosition().y(), this->_anchor.x(), this->_anchor.y(), this->_size.width(), this->_size.height());
    }
    // 最后更新颜色数据
    if (this->_flag & SpriteFlag::COLOR)
    {
        this->_renderer->updateColor(this->_color.r(), this->_color.g(), this->_color.b(), this->_color.a());
    }
    // 最后更新纹理数据
    if (this->_flag & SpriteFlag::TEXTURE)
    {
        this->_renderer->updateTexture(this->_texturePath);
    }

    // 最后清除标志位
    this->_flag = SpriteFlag::NONE;

    if (this->_color.a() > 0 && this->_size.width() > 0 && this->_size.height() > 0)
    {
        Renderer::renderers.push_back(this->_rendererId);
    }
}

Sprite::~Sprite()
{
}
